package com.runchamp;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.runchamp.util.DistanceCircleView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Created by Oryan on 05/12/2014.
 */
public class JSONAdapterRacesList extends BaseAdapter {

    Context mContext;
    LayoutInflater mInflater;
    JSONArray mJsonArray;
    boolean mChooseRace;

    public JSONAdapterRacesList(Context context, LayoutInflater inflater, boolean chooseRace) {
        mContext = context;
        mInflater = inflater;
        mJsonArray = new JSONArray();
        mChooseRace = chooseRace;
    }

    @Override
    public int getCount() {
        return mJsonArray.length();
    }

    //////BaseAdapter functions///////

    @Override
    public Object getItem(int position) {
        return mJsonArray.optJSONObject(position);
    }

    @Override
    public long getItemId(int position) {
        JSONObject json = (JSONObject) getItem(position);
        try {
            long key = json.getLong("Key");
            return key;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        // check if the view already exists, if so, no need to inflate and findViewById again!
        if (convertView == null) {
            // Inflate the custom row layout from XML
            convertView = mInflater.inflate(R.layout.row_race, null);
            // create a new "Holder" with subviews
            holder = new ViewHolder();
            holder.distanceTextView = (TextView) convertView.findViewById(R.id.text_distance);
            holder.participantsTextView = (TextView) convertView.findViewById(R.id.text_participants);
            holder.tagsTextView = (TextView) convertView.findViewById(R.id.text_race_tags);
            holder.startTimeTextView = (TextView) convertView.findViewById(R.id.text_start_time);
            holder.rowBackground = (RelativeLayout) convertView.findViewById(R.id.row_background);
            holder.unitTextView = (TextView) convertView.findViewById(R.id.text_km);
            holder.circle = (de.hdodenhof.circleimageview.CircleImageView) convertView.findViewById(R.id.row_circle);
            // hang onto this holder for future recyclage
            convertView.setTag(holder);
        } else {
            // skip all the expensive inflation/findViewById and just get the holder you already made
            holder = (ViewHolder) convertView.getTag();
        }

        // Get the current race's data in JSON form
        JSONObject jsonObject = (JSONObject) getItem(position);

        // Grab the details from the JSON
        String distance = "";
        String tags = "";
        String timeStart = "";
        String participants = "";
        Date dateTime = null;

        if (jsonObject.has("Distance")) {
            distance = jsonObject.optString("Distance");
        }
        if (jsonObject.has("Time")) {
            timeStart = jsonObject.optString("Time");
        }
        if (jsonObject.has("Tags")) {
            tags = jsonObject.optString("Tags");
        }
        if (jsonObject.has("Participants")) {
            participants = jsonObject.optString("Participants");
        }
        if (mChooseRace) {
            if (jsonObject.has("MyRace")) {
                int backgroundColor = (jsonObject.optBoolean("MyRace")) ? R.color.blue_semi_transparent : Color.WHITE;
                holder.rowBackground.setBackgroundColor(backgroundColor);
            }
        }
        if (jsonObject.has("Time")) {
            String StrTime = jsonObject.optString("Time");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            try {
                dateTime = sdf.parse(StrTime);
            } catch (ParseException e) {
                dateTime = new Date();
                e.printStackTrace();
            }
            timeStart = new SimpleDateFormat("dd.MM.yy  HH:mm").format(dateTime);
        }

        //check if date is today
        Calendar raceDate = Calendar.getInstance();
        SimpleDateFormat temp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String raceDAteFormat = temp.format(dateTime);
        int raceYear = Integer.valueOf(raceDAteFormat.substring(0, 4));
        int raceMonth = Integer.valueOf(raceDAteFormat.substring(5, 7));
        raceMonth--; //january is 0 and not 1 as the text
        int raceDay = Integer.valueOf(raceDAteFormat.substring(8, 10));
        int raceHour = Integer.valueOf(raceDAteFormat.substring(11, 13));
        int raceMin = Integer.valueOf(raceDAteFormat.substring(14, 16));

        raceDate.set(Calendar.YEAR, raceYear);
        raceDate.set(Calendar.MONTH, raceMonth);
        raceDate.set(Calendar.DAY_OF_MONTH, raceDay);

        Calendar nowDate = Calendar.getInstance();

        if (raceDate.get(Calendar.YEAR) == nowDate.get(Calendar.YEAR)
                && raceDate.get(Calendar.MONTH) == nowDate.get(Calendar.MONTH)
                && raceDate.get(Calendar.DAY_OF_MONTH) == nowDate.get(Calendar.DAY_OF_MONTH)) {
            String day = "Today";
            String h0 = "";
            String m0 = "";
            if (raceHour < 10) h0 = "0";
            if (raceMin < 10) m0 = "0";
            String time = h0 + String.valueOf(raceHour) + ":" + m0 + String.valueOf(raceMin);
            timeStart = day + "  " + time;
        }
        //check if date is tomorrow
        else {
            nowDate.add(Calendar.DATE, 1);
            if (raceDate.get(Calendar.YEAR) == nowDate.get(Calendar.YEAR)
                    && raceDate.get(Calendar.MONTH) == nowDate.get(Calendar.MONTH)
                    && raceDate.get(Calendar.DAY_OF_MONTH) == nowDate.get(Calendar.DAY_OF_MONTH)) {
                String day = "Tomorrow";
                String h0 = "";
                String m0 = "";
                if (raceHour < 10) h0 = "0";
                if (raceMin < 10) m0 = "0";
                String time = h0 + String.valueOf(raceHour) + ":" + m0 + String.valueOf(raceMin);
                timeStart = day + "  " + time;
            }
        }

        // Send these Strings to the TextViews for display
        holder.distanceTextView.setText(distance);
        holder.tagsTextView.setText(tags);
        holder.startTimeTextView.setText(timeStart);
        holder.participantsTextView.setText(participants);
        DistanceCircleView.setCircle(distance, holder.circle, holder.distanceTextView, holder.unitTextView);
        return convertView;
    }

    public void updateData(JSONArray jsonArray) {
        // update the adapter's dataset
        mJsonArray = jsonArray;
        notifyDataSetChanged();
    }


    //////Update///////

    public void sortByDistance() {
        List<JSONObject> jsons = new ArrayList<JSONObject>();
        for (int i = 0; i < getCount(); i++) {
            jsons.add((JSONObject) getItem(i));
        }
        Collections.sort(jsons, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                double aDist = (a.has("Distance")) ? a.optDouble("Distance") : 0;
                double bDist = (b.has("Distance")) ? b.optDouble("Distance") : 0;
                return Double.compare(aDist, bDist);
            }
        });
        updateData(new JSONArray(jsons));
    }

    //////Sort functions///////

    public void sortByParticipants() {
        List<JSONObject> jsons = new ArrayList<JSONObject>();
        for (int i = 0; i < getCount(); i++) {
            jsons.add((JSONObject) getItem(i));
        }
        Collections.sort(jsons, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                int aParts = (a.has("Participants")) ? a.optInt("Participants") : 0;
                int bParts = (b.has("Participants")) ? b.optInt("Participants") : 0;
                return Integer.compare(bParts, aParts);
            }
        });
        updateData(new JSONArray(jsons));
    }

    public void sortByTime() {
        List<JSONObject> jsons = new ArrayList<JSONObject>();
        for (int i = 0; i < getCount(); i++) {
            jsons.add((JSONObject) getItem(i));
        }
        Collections.sort(jsons, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                Date aTime, bTime;

                if (a.has("Time")) {
                    String aStrTime = a.optString("Time");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        aTime = sdf.parse(aStrTime);
                    } catch (ParseException e) {
                        aTime = new Date();
                        e.printStackTrace();
                    }
                } else
                    aTime = new Date();

                if (b.has("Time")) {
                    String aStrTime = b.optString("Time");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        bTime = sdf.parse(aStrTime);
                    } catch (ParseException e) {
                        bTime = new Date();
                        e.printStackTrace();
                    }
                } else
                    bTime = new Date();

                return aTime.compareTo(bTime);
            }
        });
        updateData(new JSONArray(jsons));
    }

    private static class ViewHolder {
        public TextView distanceTextView;
        public TextView participantsTextView;
        public TextView tagsTextView;
        public TextView startTimeTextView;
        public RelativeLayout rowBackground;
        public TextView unitTextView;
        public de.hdodenhof.circleimageview.CircleImageView circle;
    }
}
